using Aliyun.OSS;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.DependencyInjection;

namespace B.WMS.Good
{
    /// <summary>
    /// 阿里云OSS服务
    /// </summary>
    public class OSSService : ITransientDependency
    {
        private readonly OssClient _ossClient;
        private readonly string _bucketName;
        private readonly string _endpoint;

        public OSSService(IConfiguration configuration)
        {
            var endpoint = configuration["OSS:Endpoint"] ?? "https://oss-cn-beijing.aliyuncs.com";
            var accessKeyId = configuration["OSS:AccessKeyId"];
            var accessKeySecret = configuration["OSS:AccessKeySecret"];
            _bucketName = configuration["OSS:BucketName"] ?? "wcy1122";
            _endpoint = endpoint;

            if (string.IsNullOrEmpty(accessKeyId) || string.IsNullOrEmpty(accessKeySecret))
            {
                throw new InvalidOperationException("OSS配置信息不完整，请检查AccessKeyId和AccessKeySecret");
            }

            _ossClient = new OssClient(endpoint, accessKeyId, accessKeySecret);
        }

        /// <summary>
        /// 上传单个文件
        /// </summary>
        /// <param name="file">文件</param>
        /// <param name="folder">文件夹路径（可选）</param>
        /// <returns>文件访问URL</returns>
        public async Task<string> UploadFileAsync(IFormFile file, string folder = "upload")
        {
            try
            {
                // 生成文件名
                var fileName = $"{Guid.NewGuid()}{Path.GetExtension(file.FileName)}";
                
                // 按日期组织文件夹结构
                var datePath = $"{DateTime.Now:yyyy/MM/dd}";
                var objectName = $"{folder}/{datePath}/{fileName}";

                // 上传文件到OSS
                using (var stream = file.OpenReadStream())
                {
                    var putObjectRequest = new PutObjectRequest(_bucketName, objectName, stream);
                    
                                         // 设置正确的Content-Type，确保图片能正确显示
                     if (IsImageFile(file.FileName))
                     {
                         putObjectRequest.Metadata.ContentType = GetImageContentType(file.FileName);
                     }
                     else
                     {
                         putObjectRequest.Metadata.ContentType = file.ContentType;
                     }
                    
                    var result = _ossClient.PutObject(putObjectRequest);
                    
                    if (result.HttpStatusCode == System.Net.HttpStatusCode.OK)
                    {
                        // 返回可访问的URL，图片会直接显示而不是下载
                        return $"https://{_bucketName}.oss-cn-beijing.aliyuncs.com/{objectName}";
                    }
                    else
                    {
                        throw new Exception($"上传失败，HTTP状态码：{result.HttpStatusCode}");
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"文件上传失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 批量上传文件
        /// </summary>
        /// <param name="files">文件列表</param>
        /// <param name="folder">文件夹路径（可选）</param>
        /// <returns>上传结果列表</returns>
        public async Task<List<UploadResult>> UploadMultipleFilesAsync(IFormFileCollection files, string folder = "upload")
        {
            var results = new List<UploadResult>();
            
            foreach (var file in files)
            {
                try
                {
                    var url = await UploadFileAsync(file, folder);
                    results.Add(new UploadResult
                    {
                        FileName = file.FileName,
                        Url = url,
                        Success = true,
                        Message = "上传成功"
                    });
                }
                catch (Exception ex)
                {
                    results.Add(new UploadResult
                    {
                        FileName = file.FileName,
                        Success = false,
                        Message = $"上传失败：{ex.Message}"
                    });
                }
            }
            
            return results;
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="fileUrl">文件URL</param>
        /// <returns>是否删除成功</returns>
        public async Task<bool> DeleteFileAsync(string fileUrl)
        {
            try
            {
                // 从URL中提取对象名称
                var uri = new Uri(fileUrl);
                var objectName = uri.AbsolutePath.TrimStart('/');
                
                // 移除bucket名称部分
                if (objectName.StartsWith(_bucketName + "/"))
                {
                    objectName = objectName.Substring(_bucketName.Length + 1);
                }

                var result = _ossClient.DeleteObject(_bucketName, objectName);
                return result.HttpStatusCode == System.Net.HttpStatusCode.NoContent;
            }
            catch (Exception ex)
            {
                throw new Exception($"文件删除失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 获取文件信息
        /// </summary>
        /// <param name="fileUrl">文件URL</param>
        /// <returns>文件信息</returns>
        public async Task<FileInfo> GetFileInfoAsync(string fileUrl)
        {
            try
            {
                var uri = new Uri(fileUrl);
                var objectName = uri.AbsolutePath.TrimStart('/');
                
                if (objectName.StartsWith(_bucketName + "/"))
                {
                    objectName = objectName.Substring(_bucketName.Length + 1);
                }

                var metadata = _ossClient.GetObjectMetadata(_bucketName, objectName);
                
                return new FileInfo
                {
                    FileName = Path.GetFileName(objectName),
                    Size = metadata.ContentLength,
                    ContentType = metadata.ContentType,
                    LastModified = metadata.LastModified,
                    Url = fileUrl
                };
            }
            catch (Exception ex)
            {
                throw new Exception($"获取文件信息失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 检查Bucket是否存在
        /// </summary>
        /// <returns>是否存在</returns>
        public bool BucketExists()
        {
            try
            {
                return _ossClient.DoesBucketExist(_bucketName);
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 检查是否为图片文件
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <returns>是否为图片</returns>
        private bool IsImageFile(string fileName)
        {
            if (string.IsNullOrEmpty(fileName))
                return false;

            var extension = Path.GetExtension(fileName).ToLowerInvariant();
            return new[] { ".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp", ".svg", ".ico" }.Contains(extension);
        }

        /// <summary>
        /// 获取图片文件的Content-Type
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <returns>Content-Type</returns>
        private string GetImageContentType(string fileName)
        {
            var extension = Path.GetExtension(fileName).ToLowerInvariant();
            return extension switch
            {
                ".jpg" or ".jpeg" => "image/jpeg",
                ".png" => "image/png",
                ".gif" => "image/gif",
                ".bmp" => "image/bmp",
                ".webp" => "image/webp",
                ".svg" => "image/svg+xml",
                ".ico" => "image/x-icon",
                _ => "application/octet-stream"
            };
        }
    }

    /// <summary>
    /// 上传结果
    /// </summary>
    public class UploadResult
    {
        public string FileName { get; set; }
        public string Url { get; set; }
        public bool Success { get; set; }
        public string Message { get; set; }
    }

    /// <summary>
    /// 文件信息
    /// </summary>
    public class FileInfo
    {
        public string FileName { get; set; }
        public long Size { get; set; }
        public string ContentType { get; set; }
        public DateTime LastModified { get; set; }
        public string Url { get; set; }
    }
} 